# frozen_string_literal: true

require 'numo/optimize'

require 'rumale/utils'
require 'rumale/validation'
require 'rumale/base/classifier'

require_relative 'base_estimator'

module Rumale
  module LinearModel
    # LogisticRegression is a class that implements (multinomial) Logistic Regression.
    #
    # @note
    #   Rumale::SVM provides Logistic Regression based on LIBLINEAR.
    #   If you prefer execution speed, you should use Rumale::SVM::LogisticRegression.
    #   https://github.com/yoshoku/rumale-svm
    #
    # @example
    #   require 'rumale/linear_model/logistic_regression'
    #
    #   estimator = Rumale::LinearModel::LogisticRegression.new(reg_param: 1.0)
    #   estimator.fit(training_samples, traininig_labels)
    #   results = estimator.predict(testing_samples)
    class LogisticRegression < Rumale::LinearModel::BaseEstimator
      include Rumale::Base::Classifier

      # Return the class labels.
      # @return [Numo::Int32] (shape: [n_classes])
      attr_reader :classes

      # Create a new classifier with Logisitc Regression.
      #
      # @param reg_param [Float] The regularization parameter.
      # @param fit_bias [Boolean] The flag indicating whether to fit the bias term.
      # @param bias_scale [Float] The scale of the bias term.
      #   If fit_bias is true, the feature vector v becoms [v; bias_scale].
      # @param max_iter [Integer] The maximum number of epochs that indicates
      #   how many times the whole data is given to the training process.
      # @param tol [Float] The tolerance of loss for terminating optimization.
      # @param n_jobs [Integer] The number of jobs for running the predict methods in parallel.
      #   If nil is given, the methods do not execute in parallel.
      #   If zero or less is given, it becomes equal to the number of processors.
      #   This parameter is ignored if the Parallel gem is not loaded.
      # @param verbose [Boolean] The flag indicating whether to output loss during iteration.
      #   'iterate.dat' file is generated by numo-optimize.
      def initialize(reg_param: 1.0, fit_bias: true, bias_scale: 1.0, max_iter: 1000, tol: 1e-4, n_jobs: nil, verbose: false)
        super()
        @params = {
          reg_param: reg_param,
          fit_bias: fit_bias,
          bias_scale: bias_scale,
          max_iter: max_iter,
          tol: tol,
          n_jobs: n_jobs,
          verbose: verbose
        }
      end

      # Fit the model with given training data.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
      # @param y [Numo::Int32] (shape: [n_samples]) The labels to be used for fitting the model.
      # @return [LogisticRegression] The learned classifier itself.
      def fit(x, y)
        x = Rumale::Validation.check_convert_sample_array(x)
        y = Rumale::Validation.check_convert_label_array(y)
        Rumale::Validation.check_sample_size(x, y)

        @classes = Numo::Int32[*y.to_a.uniq.sort]
        @weight_vec, @bias_term = partial_fit(x, y)

        self
      end

      # Calculate confidence scores for samples.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to compute the scores.
      # @return [Numo::DFloat] (shape: [n_samples, n_classes]) Confidence score per sample.
      def decision_function(x)
        x = Rumale::Validation.check_convert_sample_array(x)

        x.dot(@weight_vec.transpose) + @bias_term
      end

      # Predict class labels for samples.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to predict the labels.
      # @return [Numo::Int32] (shape: [n_samples]) Predicted class label per sample.
      def predict(x)
        x = Rumale::Validation.check_convert_sample_array(x)

        n_samples, = x.shape
        decision_values = predict_proba(x)
        predicted = if enable_parallel?
                      parallel_map(n_samples) { |n| @classes[decision_values[n, true].max_index] }
                    else
                      Array.new(n_samples) { |n| @classes[decision_values[n, true].max_index] }
                    end
        Numo::Int32.asarray(predicted)
      end

      # Predict probability for samples.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to predict the probailities.
      # @return [Numo::DFloat] (shape: [n_samples, n_classes]) Predicted probability of each class per sample.
      def predict_proba(x)
        x = Rumale::Validation.check_convert_sample_array(x)

        proba = 1.0 / (Numo::NMath.exp(-decision_function(x)) + 1.0)
        return (proba.transpose / proba.sum(axis: 1)).transpose.dup if multiclass_problem?

        n_samples, = x.shape
        probs = Numo::DFloat.zeros(n_samples, 2)
        probs[true, 1] = proba
        probs[true, 0] = 1.0 - proba
        probs
      end

      private

      def partial_fit(base_x, base_y) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
        if multiclass_problem?
          fnc = proc do |w, x, y, a|
            n_features = x.shape[1]
            n_classes = y.shape[1]
            z = x.dot(w.reshape(n_classes, n_features).transpose)
            # logsumexp and softmax
            z_max = z.max(-1).expand_dims(-1).dup
            z_max[~z_max.isfinite] = 0.0
            lgsexp = Numo::NMath.log(Numo::NMath.exp(z - z_max).sum(axis: -1)).expand_dims(-1) + z_max
            t = z - lgsexp
            sftmax = Numo::NMath.exp(t)
            # loss and gradient
            loss = -(y * t).sum + 0.5 * a * w.dot(w)
            grad = (sftmax - y).transpose.dot(x).flatten.dup + a * w
            [loss, grad]
          end

          base_x = expand_feature(base_x) if fit_bias?
          onehot_y = ::Rumale::Utils.binarize_labels(base_y)
          n_classes = @classes.size
          n_features = base_x.shape[1]
          w_init = Numo::DFloat.zeros(n_classes * n_features)

          res = Numo::Optimize.minimize(
            fnc: fnc, jcb: true, x_init: w_init, args: [base_x, onehot_y, @params[:reg_param]],
            maxiter: @params[:max_iter], factr: @params[:tol] / Numo::Optimize::Lbfgsb::DBL_EPSILON,
            verbose: @params[:verbose] ? 1 : -1
          )

          split_weight(res[:x].reshape(n_classes, n_features))
        else
          fnc = proc do |w, x, y, a|
            z = 1 + Numo::NMath.exp(-y * x.dot(w))
            loss = Numo::NMath.log(z).sum + 0.5 * a * w.dot(w)
            grad = (y / z - y).dot(x) + a * w
            [loss, grad]
          end

          base_x = expand_feature(base_x) if fit_bias?
          negative_label = @classes[0]
          bin_y = Numo::Int32.cast(base_y.ne(negative_label)) * 2 - 1
          n_features = base_x.shape[1]
          w_init = Numo::DFloat.zeros(n_features)

          res = Numo::Optimize.minimize(
            fnc: fnc, jcb: true, x_init: w_init, args: [base_x, bin_y, @params[:reg_param]],
            maxiter: @params[:max_iter], factr: @params[:tol] / Numo::Optimize::Lbfgsb::DBL_EPSILON,
            verbose: @params[:verbose] ? 1 : -1
          )

          split_weight(res[:x])
        end
      end

      def multiclass_problem?
        @classes.size > 2
      end
    end
  end
end
